package com.ylkj.example;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class EmployeeHandler {

    @Autowired
    private EmployeeDao employeeDao;
    
    
    @Autowired
    private DepartmentDao departmentDao;
    
    /**
     * 查询
     */
    @RequestMapping("query")
    public String query(Map<String,Object> map){
        map.put("allEmployees", employeeDao.getAll());
        return "list";
    }
    
    @RequestMapping("readyData")
    public String readyData(Map<String,Object> map){
        map.put("department", departmentDao.getDepartments());
        map.put("employee", new Employee());
        //map.put("actionType", "add");
        return "addPage";
    }
    
    @RequestMapping("add")
    public String addEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/query.do";
    }
    
    @RequestMapping(value="delete/{id}",method=RequestMethod.GET)
    public String delete(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/query";
    }
    
    @RequestMapping("edit/{id}")
    public String updateEmployee(@PathVariable("id") Integer id,
            Map<String,Object> map){
        map.put("employee", employeeDao.get(id));
        map.put("actionType", "update");
        map.put("department", departmentDao.getDepartments());
        return "addPage";
    }
    
    @RequestMapping("update")
    public String update(@RequestParam(value="id") Integer id,Employee employee){
        employeeDao.update(id, employee);
        return "redirect:/query";
    }
    
    @ModelAttribute
    public void solvePro(@RequestParam(value="id",required=false)Integer id,
            Map<String,Object> map){
        if (id != null) {
            map.put("employee", employeeDao.get(id));
        }
    }
}